package com.haste.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.haste.system.domain.vo.TreeNode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommonService {
    public List<TreeNode> list2Tree(List<TreeNode> sources){
        List<TreeNode> rootList = sources
                .stream()
                .filter(node -> StrUtil.isBlank(node.getParentId()))
                .collect(Collectors.toList());
        return this.buildTree(sources,rootList);
    }

    private List<TreeNode> buildTree(List<TreeNode> sources, List<TreeNode> parentNodes){
        parentNodes = parentNodes.stream()
                .sorted(Comparator.comparing(TreeNode::getSort))
                .collect(Collectors.toList());

        List<TreeNode> resList = new ArrayList<>();
        List<TreeNode> childrenList = new ArrayList<>();
        for (TreeNode parent : parentNodes) {
            List<TreeNode> children = sources.stream()
                    .filter(source -> StrUtil.equals(parent.getId(), source.getParentId()))
                    .collect(Collectors.toList());

            if (CollUtil.isNotEmpty(children)){
                children = children.stream()
                        .sorted(Comparator.comparing(TreeNode::getSort))
                        .collect(Collectors.toList());
                childrenList.addAll(children);
            }
            parent.setChildren(children);
            resList.add(parent);
        }
        if (CollUtil.isNotEmpty(childrenList)){
            this.buildTree(sources,childrenList);
        }
        return resList;
    }
}
